home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python1.4_Source / Python / marshal.c < prev    next >
C/C++ Source or Header  |  1998-06-24  |  14KB  |  676 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Write Python objects to files and read them back.
  33.    This is intended for writing and reading compiled Python code only;
  34.    a true persistent storage facility would be much harder, since
  35.    it would have to take circular links and sharing into account. */
  36.  
  37. #include "allobjects.h"
  38. #include "modsupport.h"
  39. #include "longintrepr.h"
  40. #include "compile.h"
  41. #include "marshal.h"
  42.  
  43. #include <errno.h>
  44.  
  45. #define TYPE_NULL    '0'
  46. #define TYPE_NONE    'N'
  47. #define TYPE_ELLIPSIS   '.'
  48. #define TYPE_INT    'i'
  49. #define TYPE_FLOAT    'f'
  50. #define TYPE_COMPLEX    'x'
  51. #define TYPE_LONG    'l'
  52. #define TYPE_STRING    's'
  53. #define TYPE_TUPLE    '('
  54. #define TYPE_LIST    '['
  55. #define TYPE_DICT    '{'
  56. #define TYPE_CODE    'c'
  57. #define TYPE_UNKNOWN    '?'
  58.  
  59. typedef struct {
  60.     FILE *fp;
  61.     int error;
  62.     /* If fp == NULL, the following are valid: */
  63.     object *str;
  64.     char *ptr;
  65.     char *end;
  66. } WFILE;
  67.  
  68. #include "protos/marshal_protos1.h"
  69.  
  70. #define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \
  71.               else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \
  72.                else w_more(c, p)
  73.  
  74. static void
  75. w_more(c, p)
  76.     char c;
  77.     WFILE *p;
  78. {
  79.     int size, newsize;
  80.     if (p->str == NULL)
  81.         return; /* An error already occurred */
  82.     size = getstringsize(p->str);
  83.     newsize = size + 1024;
  84.     if (resizestring(&p->str, newsize) != 0) {
  85.         p->ptr = p->end = NULL;
  86.     }
  87.     else {
  88.         p->ptr = GETSTRINGVALUE((stringobject *)p->str) + size;
  89.         p->end = GETSTRINGVALUE((stringobject *)p->str) + newsize;
  90.         *p->ptr++ = c;
  91.     }
  92. }
  93.  
  94. static void
  95. w_string(s, n, p)
  96.     char *s;
  97.     int n;
  98.     WFILE *p;
  99. {
  100.     if (p->fp != NULL) {
  101.         fwrite(s, 1, n, p->fp);
  102.     }
  103.     else {
  104.         while (--n >= 0) {
  105.             w_byte(*s, p);
  106.             s++;
  107.         }
  108.     }
  109. }
  110.  
  111. static void
  112. w_short(x, p)
  113.     int x;
  114.     WFILE *p;
  115. {
  116.     w_byte( x      & 0xff, p);
  117.     w_byte((x>> 8) & 0xff, p);
  118. }
  119.  
  120. static void
  121. w_long(x, p)
  122.     long x;
  123.     WFILE *p;
  124. {
  125.     w_byte((int)( x      & 0xff), p);
  126.     w_byte((int)((x>> 8) & 0xff), p);
  127.     w_byte((int)((x>>16) & 0xff), p);
  128.     w_byte((int)((x>>24) & 0xff), p);
  129. }
  130.  
  131. static void
  132. w_object(v, p)
  133.     object *v;
  134.     WFILE *p;
  135. {
  136.     int i, n;
  137.     
  138.     if (v == NULL)
  139.         w_byte(TYPE_NULL, p);
  140.     else if (v == None)
  141.         w_byte(TYPE_NONE, p);
  142.     else if (v == Py_Ellipsis)
  143.             w_byte(TYPE_ELLIPSIS, p);  
  144.     else if (is_intobject(v)) {
  145.         w_byte(TYPE_INT, p);
  146.         w_long(getintvalue(v), p);
  147.     }
  148.     else if (is_longobject(v)) {
  149.         longobject *ob = (longobject *)v;
  150.         w_byte(TYPE_LONG, p);
  151.         n = ob->ob_size;
  152.         w_long((long)n, p);
  153.         if (n < 0)
  154.             n = -n;
  155.         for (i = 0; i < n; i++)
  156.             w_short(ob->ob_digit[i], p);
  157.     }
  158.     else if (is_floatobject(v)) {
  159.         extern void float_buf_repr PROTO((char *, floatobject *));
  160.         char buf[256]; /* Plenty to format any double */
  161.         float_buf_repr(buf, (floatobject *)v);
  162.         n = strlen(buf);
  163.         w_byte(TYPE_FLOAT, p);
  164.         w_byte(n, p);
  165.         w_string(buf, n, p);
  166.     }
  167. #ifndef WITHOUT_COMPLEX
  168.     else if (is_complexobject(v)) {
  169.         extern void float_buf_repr PROTO((char *, floatobject *));
  170.         char buf[256]; /* Plenty to format any double */
  171.         floatobject *temp;
  172.         w_byte(TYPE_COMPLEX, p);
  173.         temp = (floatobject*)newfloatobject(PyComplex_RealAsDouble(v));
  174.         float_buf_repr(buf, temp);
  175.         DECREF(temp);
  176.         n = strlen(buf);
  177.         w_byte(n, p);
  178.         w_string(buf, n, p);
  179.         temp = (floatobject*)newfloatobject(PyComplex_ImagAsDouble(v));
  180.         float_buf_repr(buf, temp);
  181.         DECREF(temp);
  182.         n = strlen(buf);
  183.         w_byte(n, p);
  184.         w_string(buf, n, p);
  185.     }
  186. #endif
  187.     else if (is_stringobject(v)) {
  188.         w_byte(TYPE_STRING, p);
  189.         n = getstringsize(v);
  190.         w_long((long)n, p);
  191.         w_string(getstringvalue(v), n, p);
  192.     }
  193.     else if (is_tupleobject(v)) {
  194.         w_byte(TYPE_TUPLE, p);
  195.         n = gettuplesize(v);
  196.         w_long((long)n, p);
  197.         for (i = 0; i < n; i++) {
  198.             w_object(GETTUPLEITEM(v, i), p);
  199.         }
  200.     }
  201.     else if (is_listobject(v)) {
  202.         w_byte(TYPE_LIST, p);
  203.         n = getlistsize(v);
  204.         w_long((long)n, p);
  205.         for (i = 0; i < n; i++) {
  206.             w_object(getlistitem(v, i), p);
  207.         }
  208.     }
  209.     else if (is_dictobject(v)) {
  210.         int pos;
  211.         object *key, *value;
  212.         w_byte(TYPE_DICT, p);
  213.         /* This one is NULL object terminated! */
  214.         pos = 0;
  215.         while (mappinggetnext(v, &pos, &key, &value)) {
  216.             w_object(key, p);
  217.             w_object(value, p);
  218.         }
  219.         w_object((object *)NULL, p);
  220.     }
  221.     else if (is_codeobject(v)) {
  222.         codeobject *co = (codeobject *)v;
  223.         w_byte(TYPE_CODE, p);
  224.         w_short(co->co_argcount, p);
  225.         w_short(co->co_nlocals, p);
  226.         w_short(co->co_flags, p);
  227.         w_object((object *)co->co_code, p);
  228.         w_object(co->co_consts, p);
  229.         w_object(co->co_names, p);
  230.         w_object(co->co_varnames, p);
  231.         w_object(co->co_filename, p);
  232.         w_object(co->co_name, p);
  233.     }
  234.     else {
  235.         w_byte(TYPE_UNKNOWN, p);
  236.         p->error = 1;
  237.     }
  238. }
  239.  
  240. void
  241. wr_long(x, fp)
  242.     long x;
  243.     FILE *fp;
  244. {
  245.     WFILE wf;
  246.     wf.fp = fp;
  247.     wf.error = 0;
  248.     w_long(x, &wf);
  249. }
  250.  
  251. void
  252. wr_object(x, fp)
  253.     object *x;
  254.     FILE *fp;
  255. {
  256.     WFILE wf;
  257.     wf.fp = fp;
  258.     wf.error = 0;
  259.     w_object(x, &wf);
  260. }
  261.  
  262. typedef WFILE RFILE; /* Same struct with different invariants */
  263.  
  264. #include "protos/marshal_protos2.h"
  265.  
  266. #define rs_byte(p) (((p)->ptr != (p)->end) ? (unsigned char)*(p)->ptr++ : EOF)
  267.  
  268. #define r_byte(p) ((p)->fp ? getc((p)->fp) : rs_byte(p))
  269.  
  270. static int
  271. r_string(s, n, p)
  272.     char *s;
  273.     int n;
  274.     RFILE *p;
  275. {
  276.     if (p->fp != NULL)
  277.         return fread(s, 1, n, p->fp);
  278.     if (p->end - p->ptr < n)
  279.         n = p->end - p->ptr;
  280.     memcpy(s, p->ptr, n);
  281.     p->ptr += n;
  282.     return n;
  283. }
  284.  
  285. static int
  286. r_short(p)
  287.     RFILE *p;
  288. {
  289.     register short x;
  290.     x = r_byte(p);
  291.     x |= r_byte(p) << 8;
  292.     /* XXX If your short is > 16 bits, add sign-extension here!!! */
  293.     return x;
  294. }
  295.  
  296. static long
  297. r_long(p)
  298.     RFILE *p;
  299. {
  300.     register long x;
  301.     register FILE *fp = p->fp;
  302.     if (fp) {
  303.         x = getc(fp);
  304.         x |= (long)getc(fp) << 8;
  305.         x |= (long)getc(fp) << 16;
  306.         x |= (long)getc(fp) << 24;
  307.     }
  308.     else {
  309.         x = rs_byte(p);
  310.         x |= (long)rs_byte(p) << 8;
  311.         x |= (long)rs_byte(p) << 16;
  312.         x |= (long)rs_byte(p) << 24;
  313.     }
  314.     /* XXX If your long is > 32 bits, add sign-extension here!!! */
  315.     return x;
  316. }
  317.  
  318. static object *
  319. r_object(p)
  320.     RFILE *p;
  321. {
  322.     object *v, *v2;
  323.     long i, n;
  324.     int type = r_byte(p);
  325.     
  326.     switch (type) {
  327.     
  328.     case EOF:
  329.         err_setstr(EOFError, "EOF read where object expected");
  330.         return NULL;
  331.     
  332.     case TYPE_NULL:
  333.         return NULL;
  334.     
  335.     case TYPE_NONE:
  336.         INCREF(None);
  337.         return None;
  338.     
  339.     case TYPE_ELLIPSIS:
  340.         INCREF(Py_Ellipsis);
  341.         return Py_Ellipsis;
  342.     
  343.     case TYPE_INT:
  344.         return newintobject(r_long(p));
  345.     
  346.     case TYPE_LONG:
  347.         {
  348.             int size;
  349.             longobject *ob;
  350.             n = r_long(p);
  351.             size = n<0 ? -n : n;
  352.             ob = alloclongobject(size);
  353.             if (ob == NULL)
  354.                 return NULL;
  355.             ob->ob_size = n;
  356.             for (i = 0; i < size; i++)
  357.                 ob->ob_digit[i] = r_short(p);
  358.             return (object *)ob;
  359.         }
  360.     
  361.     case TYPE_FLOAT:
  362.         {
  363.             extern double atof PROTO((const char *));
  364.             char buf[256];
  365.             n = r_byte(p);
  366.             if (r_string(buf, (int)n, p) != n) {
  367.                 err_setstr(EOFError,
  368.                     "EOF read where object expected");
  369.                 return NULL;
  370.             }
  371.             buf[n] = '\0';
  372.             return newfloatobject(atof(buf));
  373.         }
  374.     
  375. #ifndef WITHOUT_COMPLEX
  376.     case TYPE_COMPLEX:
  377.         {
  378.             extern double atof PROTO((const char *));
  379.             char buf[256];
  380.             Py_complex c;
  381.             n = r_byte(p);
  382.             if (r_string(buf, (int)n, p) != n) {
  383.                 err_setstr(EOFError,
  384.                     "EOF read where object expected");
  385.                 return NULL;
  386.             }
  387.             buf[n] = '\0';
  388.             c.real = atof(buf);
  389.             n = r_byte(p);
  390.             if (r_string(buf, (int)n, p) != n) {
  391.                 err_setstr(EOFError,
  392.                     "EOF read where object expected");
  393.                 return NULL;
  394.             }
  395.             buf[n] = '\0';
  396.             c.imag = atof(buf);
  397.             return newcomplexobject(c);
  398.         }
  399. #endif
  400.     
  401.     case TYPE_STRING:
  402.         n = r_long(p);
  403.         v = newsizedstringobject((char *)NULL, n);
  404.         if (v != NULL) {
  405.             if (r_string(getstringvalue(v), (int)n, p) != n) {
  406.                 DECREF(v);
  407.                 v = NULL;
  408.                 err_setstr(EOFError,
  409.                     "EOF read where object expected");
  410.             }
  411.         }
  412.         return v;
  413.     
  414.     case TYPE_TUPLE:
  415.         n = r_long(p);
  416.         v = newtupleobject((int)n);
  417.         if (v == NULL)
  418.             return v;
  419.         for (i = 0; i < n; i++) {
  420.             v2 = r_object(p);
  421.             if ( v2 == NULL ) {
  422.                 DECREF(v);
  423.                 v = NULL;
  424.                 break;
  425.             }
  426.             SETTUPLEITEM(v, (int)i, v2);
  427.         }
  428.         return v;
  429.     
  430.     case TYPE_LIST:
  431.         n = r_long(p);
  432.         v = newlistobject((int)n);
  433.         if (v == NULL)
  434.             return v;
  435.         for (i = 0; i < n; i++) {
  436.             v2 = r_object(p);
  437.             if ( v2 == NULL ) {
  438.                 DECREF(v);
  439.                 v = NULL;
  440.                 break;
  441.             }
  442.             setlistitem(v, (int)i, v2);
  443.         }
  444.         return v;
  445.     
  446.     case TYPE_DICT:
  447.         v = newdictobject();
  448.         if (v == NULL)
  449.             return NULL;
  450.         for (;;) {
  451.             object *key, *val;
  452.             key = r_object(p);
  453.             if (key == NULL)
  454.                 break; /* XXX Assume TYPE_NULL, not an error */
  455.             val = r_object(p);
  456.             if (val != NULL)
  457.                 dict2insert(v, key, val);
  458.             DECREF(key);
  459.             XDECREF(val);
  460.         }
  461.         return v;
  462.     
  463.     case TYPE_CODE:
  464.         {
  465.             int argcount = r_short(p);
  466.             int nlocals = r_short(p);
  467.             int flags = r_short(p);
  468.             object *code = NULL;
  469.             object *consts = NULL;
  470.             object *names = NULL;
  471.             object *varnames = NULL;
  472.             object *filename = NULL;
  473.             object *name = NULL;
  474.             
  475.             code = r_object(p);
  476.             if (code) consts = r_object(p);
  477.             if (consts) names = r_object(p);
  478.             if (names) varnames = r_object(p);
  479.             if (varnames) filename = r_object(p);
  480.             if (filename) name = r_object(p);
  481.             
  482.             if (!err_occurred()) {
  483.                 v = (object *) newcodeobject(
  484.                     argcount, nlocals, flags, 
  485.                     code, consts, names, varnames,
  486.                     filename, name);
  487.             }
  488.             else
  489.                 v = NULL;
  490.             XDECREF(code);
  491.             XDECREF(consts);
  492.             XDECREF(names);
  493.             XDECREF(varnames);
  494.             XDECREF(filename);
  495.             XDECREF(name);
  496.  
  497.         }
  498.         return v;
  499.     
  500.     default:
  501.         /* Bogus data got written, which isn't ideal.
  502.            This will let you keep working and recover. */
  503.         INCREF(None);
  504.         return None;
  505.     
  506.     }
  507. }
  508.  
  509. long
  510. rd_long(fp)
  511.     FILE *fp;
  512. {
  513.     RFILE rf;
  514.     rf.fp = fp;
  515.     return r_long(&rf);
  516. }
  517.  
  518. object *
  519. rd_object(fp)
  520.     FILE *fp;
  521. {
  522.     RFILE rf;
  523.     if (err_occurred()) {
  524.         fatal("XXX rd_object called with exception set"); /* tmp */
  525.         fprintf(stderr, "XXX rd_object called with exception set\n");
  526.         return NULL;
  527.     }
  528.     rf.fp = fp;
  529.     return r_object(&rf);
  530. }
  531.  
  532. object *
  533. rds_object(str, len)
  534.     char *str;
  535.     int len;
  536. {
  537.     RFILE rf;
  538.     if (err_occurred()) {
  539.         fprintf(stderr, "XXX rds_object called with exception set\n");
  540.         return NULL;
  541.     }
  542.     rf.fp = NULL;
  543.     rf.str = NULL;
  544.     rf.ptr = str;
  545.     rf.end = str + len;
  546.     return r_object(&rf);
  547. }
  548.  
  549. object *
  550. PyMarshal_WriteObjectToString(x) /* wrs_object() */
  551.     object *x;
  552. {
  553.     WFILE wf;
  554.     wf.fp = NULL;
  555.     wf.str = newsizedstringobject((char *)NULL, 50);
  556.     if (wf.str == NULL)
  557.         return NULL;
  558.     wf.ptr = GETSTRINGVALUE((stringobject *)wf.str);
  559.     wf.end = wf.ptr + getstringsize(wf.str);
  560.     wf.error = 0;
  561.     w_object(x, &wf);
  562.     if (wf.str != NULL)
  563.         resizestring(&wf.str,
  564.             (int) (wf.ptr - GETSTRINGVALUE((stringobject *)wf.str)));
  565.     if (wf.error) {
  566.         XDECREF(wf.str);
  567.         err_setstr(ValueError, "unmarshallable object");
  568.         return NULL;
  569.     }
  570.     return wf.str;
  571. }
  572.  
  573. /* And an interface for Python programs... */
  574.  
  575. static object *
  576. marshal_dump(self, args)
  577.     object *self;
  578.     object *args;
  579. {
  580.     WFILE wf;
  581.     object *x;
  582.     object *f;
  583.     if (!getargs(args, "(OO)", &x, &f))
  584.         return NULL;
  585.     if (!is_fileobject(f)) {
  586.         err_setstr(TypeError, "marshal.dump() 2nd arg must be file");
  587.         return NULL;
  588.     }
  589.     wf.fp = getfilefile(f);
  590.     wf.str = NULL;
  591.     wf.ptr = wf.end = NULL;
  592.     wf.error = 0;
  593.     w_object(x, &wf);
  594.     if (wf.error) {
  595.         err_setstr(ValueError, "unmarshallable object");
  596.         return NULL;
  597.     }
  598.     INCREF(None);
  599.     return None;
  600. }
  601.  
  602. static object *
  603. marshal_load(self, args)
  604.     object *self;
  605.     object *args;
  606. {
  607.     RFILE rf;
  608.     object *f;
  609.     object *v;
  610.     if (!getargs(args, "O", &f))
  611.         return NULL;
  612.     if (!is_fileobject(f)) {
  613.         err_setstr(TypeError, "marshal.load() arg must be file");
  614.         return NULL;
  615.     }
  616.     rf.fp = getfilefile(f);
  617.     rf.str = NULL;
  618.     rf.ptr = rf.end = NULL;
  619.     err_clear();
  620.     v = r_object(&rf);
  621.     if (err_occurred()) {
  622.         XDECREF(v);
  623.         v = NULL;
  624.     }
  625.     return v;
  626. }
  627.  
  628. static object *
  629. marshal_dumps(self, args)
  630.     object *self;
  631.     object *args;
  632. {
  633.     object *x;
  634.     if (!getargs(args, "O", &x))
  635.         return NULL;
  636.     return PyMarshal_WriteObjectToString(x);
  637. }
  638.  
  639. static object *
  640. marshal_loads(self, args)
  641.     object *self;
  642.     object *args;
  643. {
  644.     RFILE rf;
  645.     object *v;
  646.     char *s;
  647.     int n;
  648.     if (!getargs(args, "s#", &s, &n))
  649.         return NULL;
  650.     rf.fp = NULL;
  651.     rf.str = args;
  652.     rf.ptr = s;
  653.     rf.end = s + n;
  654.     err_clear();
  655.     v = r_object(&rf);
  656.     if (err_occurred()) {
  657.         XDECREF(v);
  658.         v = NULL;
  659.     }
  660.     return v;
  661. }
  662.  
  663. static struct methodlist marshal_methods[] = {
  664.     {"dump",    marshal_dump},
  665.     {"load",    marshal_load},
  666.     {"dumps",    marshal_dumps},
  667.     {"loads",    marshal_loads},
  668.     {NULL,        NULL}        /* sentinel */
  669. };
  670.  
  671. void
  672. initmarshal()
  673. {
  674.     (void) initmodule("marshal", marshal_methods);
  675. }
  676.